/**
 * @api post model.
 *
 * User: yunshengzhu
 * Date: 2020/12/4
 * Time: 下午2:26
 */
package model

import "time"

func CreateCard(obj CardDb) error {
	return db.Create(&obj).Error
}

func GetCardNumber(cardNumber string) (obj CardDb, err error) {
	return obj, db.Where("card_number=?", cardNumber).First(&obj).Error
}

func UpdateCard(obj CardDb) error {
	return db.Select("status,use_time,to_user_id,send_time").Where("card_number=?", obj.CardNumber).Updates(obj).Error
}

func GetCardCount(userId int64, status []int64) (int64, error) {
	count := CardCountDb{}
	err := db.Select("count(*) as count").Where("user_id=? and status in ?", userId, status).Take(&count).Error
	return count.Count, err
}

func GetCardList(userId int64, status []int64, page, size int) (list []CardDb, err error) {
	list = make([]CardDb, 0)
	err = db.Where("user_id=? and status in ?", userId, status).Offset((page - 1) * size).Limit(size).Find(&list).Error
	return list, err
}

func GetCardOrderNumberCount(orderNumber string) (int64, error) {
	count := CardCountDb{}
	err := db.Select("count(*) as count").Where("order_number=?", orderNumber).Take(&count).Error
	return count.Count, err
}

func Recycle() error {
	sql := "UPDATE t_card SET `status`=0,send_time=0 where to_user_id=0 and send_time < ? and `status`=2"
	return db.Exec(sql, time.Now().Unix()-3600*24).Error
}
